package com.changgou.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.dao.*;
import com.changgou.entity.IdWorker;
import com.changgou.goods.pojo.*;
import com.changgou.service.SpuService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 商品spu信息业务逻辑层
 *
 * @author gaofeng
 * @date 2025/4/20 10:52
 */
@Service
public class SpuServiceImpl implements SpuService {
    @Resource
    private SpuMapper spuMapper;

    @Resource
    private SkuMapper skuMapper;

    @Resource
    private CategoryMapper categoryMapper;

    @Resource
    private CategoryBrandMapper categoryBrandMapper;

    @Resource
    private BrandMapper brandMapper;

    @Resource
    private IdWorker idWorker;

    @Override
    public void audit(Long spuId) {
        Spu spu = spuMapper.selectByPrimaryKey(spuId);
        if ("1".equals(spu.getIsDelete())) {
            throw new RuntimeException("该商品已删除");
        }

        spu.setStatus("1");
        spu.setIsMarketable("1");
        spuMapper.updateByPrimaryKeySelective(spu);
    }

    @Override
    public void saveGoods(Goods goods) {
        Spu spu = goods.getSpu();
        Long id = spu.getId();
        if (id == null) {
            spu.setId(idWorker.nextId());
            spu.setIsMarketable("1");
            spuMapper.insertSelective(spu);
        } else {
            spuMapper.updateByPrimaryKeySelective(spu);

            Sku sku = new Sku();
            sku.setSpuId(spu.getId());
            skuMapper.delete(sku);
        }

        Date date = new Date();
        for (Sku sku : goods.getSkuList()) {
            sku.setId(idWorker.nextId());
            sku.setSpuId(spu.getId());
            sku.setName(buildSkuName(spu, sku));
            sku.setCreateTime(date);
            sku.setUpdateTime(date);
            sku.setCategoryId(spu.getCategory3Id());
            Category category = categoryMapper.selectByPrimaryKey(spu.getCategory3Id());
            sku.setCategoryName(category.getName());
            Brand brand = brandMapper.selectByPrimaryKey(spu.getBrandId());
            sku.setBrandName(brand.getName());

            skuMapper.insertSelective(sku);
        }

        CategoryBrand categoryBrand = new CategoryBrand();
        categoryBrand.setBrandId(spu.getBrandId());
        categoryBrand.setCategoryId(spu.getCategory3Id());
        if (categoryBrandMapper.selectOne(categoryBrand) == null) {
            categoryBrandMapper.insertSelective(categoryBrand);
        }
    }

    @Override
    public Goods findGoodBySpuId(Long spuId) {
        Spu spu = spuMapper.selectByPrimaryKey(spuId);

        Sku sku = new Sku();
        sku.setSpuId(spuId);
        List<Sku> skus = skuMapper.select(sku);

        Goods goods = new Goods();
        goods.setSpu(spu);
        goods.setSkuList(skus);
        return goods;
    }

    private String buildSkuName(Spu spu, Sku sku) {
        StringBuilder name = new StringBuilder(spu.getName());
        String spec = sku.getSpec();
        if (StringUtils.isBlank(spec)) {
            return name.toString();
        }

        Map<String, String> specMap = JSON.parseObject(spec, Map.class);
        for (Map.Entry<String, String> specEntry : specMap.entrySet()) {
            name.append(" ").append(specEntry.getValue());
        }

        return name.toString();
    }

    /**
     * Spu条件+分页查询
     *
     * @param spu  查询条件
     * @param page 页码
     * @param size 页大小
     * @return 分页结果
     */
    @Override
    public PageInfo<Spu> findPage(Spu spu, int page, int size) {
        //分页
        PageHelper.startPage(page, size);
        //搜索条件构建
        Example example = createExample(spu);
        //执行搜索
        return new PageInfo<>(spuMapper.selectByExample(example));
    }

    /**
     * Spu分页查询
     *
     * @param page
     * @param size
     * @return
     */
    @Override
    public PageInfo<Spu> findPage(int page, int size) {
        //静态分页
        PageHelper.startPage(page, size);
        //分页查询
        return new PageInfo<>(spuMapper.selectAll());
    }

    /**
     * Spu条件查询
     *
     * @param spu
     * @return
     */
    @Override
    public List<Spu> findList(Spu spu) {
        //构建查询条件
        Example example = createExample(spu);
        //根据构建的条件查询数据
        return spuMapper.selectByExample(example);
    }


    /**
     * Spu构建查询对象
     *
     * @param spu
     * @return
     */
    public Example createExample(Spu spu) {
        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        if (spu != null) {
            // 主键
            if (spu.getId() != null) {
                criteria.andEqualTo("id", spu.getId());
            }
            // 货号
            if (!StringUtils.isEmpty(spu.getSn())) {
                criteria.andEqualTo("sn", spu.getSn());
            }
            // SPU名
            if (!StringUtils.isEmpty(spu.getName())) {
                criteria.andLike("name", "%" + spu.getName() + "%");
            }
            // 副标题
            if (!StringUtils.isEmpty(spu.getCaption())) {
                criteria.andEqualTo("caption", spu.getCaption());
            }
            // 品牌ID
            if (spu.getBrandId() != null) {
                criteria.andEqualTo("brandId", spu.getBrandId());
            }
            // 一级分类
            if (spu.getCategory1Id() != null) {
                criteria.andEqualTo("category1Id", spu.getCategory1Id());
            }
            // 二级分类
            if (spu.getCategory2Id() != null) {
                criteria.andEqualTo("category2Id", spu.getCategory2Id());
            }
            // 三级分类
            if (spu.getCategory3Id() != null) {
                criteria.andEqualTo("category3Id", spu.getCategory3Id());
            }
            // 模板ID
            if (spu.getTemplateId() != null) {
                criteria.andEqualTo("templateId", spu.getTemplateId());
            }
            // 运费模板id
            if (spu.getFreightId() != null) {
                criteria.andEqualTo("freightId", spu.getFreightId());
            }
            // 图片
            if (!StringUtils.isEmpty(spu.getImage())) {
                criteria.andEqualTo("image", spu.getImage());
            }
            // 图片列表
            if (!StringUtils.isEmpty(spu.getImages())) {
                criteria.andEqualTo("images", spu.getImages());
            }
            // 售后服务
            if (!StringUtils.isEmpty(spu.getSaleService())) {
                criteria.andEqualTo("saleService", spu.getSaleService());
            }
            // 介绍
            if (!StringUtils.isEmpty(spu.getIntroduction())) {
                criteria.andEqualTo("introduction", spu.getIntroduction());
            }
            // 规格列表
            if (!StringUtils.isEmpty(spu.getSpecItems())) {
                criteria.andEqualTo("specItems", spu.getSpecItems());
            }
            // 参数列表
            if (!StringUtils.isEmpty(spu.getParaItems())) {
                criteria.andEqualTo("paraItems", spu.getParaItems());
            }
            // 销量
            if (spu.getSaleNum() != null) {
                criteria.andEqualTo("saleNum", spu.getSaleNum());
            }
            // 评论数
            if (spu.getCommentNum() != null) {
                criteria.andEqualTo("commentNum", spu.getCommentNum());
            }
            // 是否上架
            if (!StringUtils.isEmpty(spu.getIsMarketable())) {
                criteria.andEqualTo("isMarketable", spu.getIsMarketable());
            }
            // 是否启用规格
            if (!StringUtils.isEmpty(spu.getIsEnableSpec())) {
                criteria.andEqualTo("isEnableSpec", spu.getIsEnableSpec());
            }
            // 是否删除
            if (!StringUtils.isEmpty(spu.getIsDelete())) {
                criteria.andEqualTo("isDelete", spu.getIsDelete());
            }
            // 审核状态
            if (!StringUtils.isEmpty(spu.getStatus())) {
                criteria.andEqualTo("status", spu.getStatus());
            }
        }

        return example;
    }

    /**
     * 删除
     *
     * @param id
     */
    @Override
    public void delete(Long id) {
        spuMapper.deleteByPrimaryKey(id);
    }

    /**
     * 修改Spu
     *
     * @param spu
     */
    @Override
    public void update(Spu spu) {
        spuMapper.updateByPrimaryKey(spu);
    }

    /**
     * 增加Spu
     *
     * @param spu
     */
    @Override
    public void add(Spu spu) {
        spuMapper.insert(spu);
    }

    /**
     * 根据ID查询Spu
     *
     * @param id
     * @return
     */
    @Override
    public Spu findById(Long id) {
        return spuMapper.selectByPrimaryKey(id);
    }

    /**
     * 查询Spu全部数据
     *
     * @return
     */
    @Override
    public List<Spu> findAll() {
        return spuMapper.selectAll();
    }

    @Override
    public void offShelve(Long spuId) {
        Spu spu = spuMapper.selectByPrimaryKey(spuId);
        if ("1".equals(spu.getIsDelete())) {
            throw new RuntimeException("不能对已删除商品进行下架操作！");
        }

        spu.setIsMarketable("0");
        spuMapper.updateByPrimaryKey(spu);
    }

    @Override
    public void onShelve(Long spuId) {
        Spu spu = spuMapper.selectByPrimaryKey(spuId);
        if ("1".equals(spu.getIsMarketable())) {
            throw new RuntimeException("不能对已删除商品进行下架操作！");
        }

        if (!"1".equals(spu.getStatus())) {
            throw new RuntimeException("商品未通过审核，不能上架！");
        }

        spu.setIsMarketable("1");
        spuMapper.updateByPrimaryKey(spu);
    }

    @Override
    public int batchOnShelve(List<Long> spuIds) {
        Spu spu = new Spu();
        spu.setIsMarketable("1");

        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("id", spuIds);
        criteria.andEqualTo("isMarketable", "0");
        criteria.andEqualTo("status", "1");
        criteria.andEqualTo("isDelete", "0");
        return spuMapper.updateByExample(spu, example);
    }
}
